package com.jf.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-09-03
 * Time:18:47
 */
@WebFilter(urlPatterns = "/exercise/show/*", initParams = {@WebInitParam(name = "forbiddenWords", value = "苹果,香蕉")})
public class TopicFilter implements Filter {
    private String[] forbiddenWords = null;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        forbiddenWords = filterConfig.getInitParameter("forbiddenWords").split(",");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        req.setAttribute("username", req.getParameter("username"));
        String content = req.getParameter("content");
        req.setAttribute("content", content);
        for (String forbiddenWord : forbiddenWords) {
            if (content.contains(forbiddenWord)) {
                req.setAttribute("error", "评论存在违禁词" + forbiddenWord);
                req.getRequestDispatcher("/exercise/topic.jsp").forward(req, servletResponse);
                return;
            }
        }
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }
}
